<template>
  <page-layout>
    <a-row :gutter="[10, 10]">
      <!-- 中心区域 -->
      <a-col :span="24">
        <a-card>
          <div class="mb-20">
            <!-- 查询参数 -->
            <pro-query
              :searchParam="searchParam.params"
              @on-search="search"
              @on-reset="onReset"
            ></pro-query>
          </div>
          <!-- 列表 -->
          <pro-table
            ref="tableRef"
            :fetch="fetch"
            :columns="columns"
            :operate="operate"
            :toolbar="toolbar"
            :param="state.param"
            :pagination="pagination"
          >
          </pro-table>
        </a-card>
      </a-col>
    </a-row>
  </page-layout>
</template>

<script>
import { message, modal } from "ant-design-vue";

import { page, remove } from "@/api/module/preferential-allocation";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { filterEmptyByObject } from "@/tools/common";
import { reactive, createVNode, ref, onMounted, onActivated } from "vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import moment from 'moment'
import dictEnum from "@/const/dict";
import { getDictByCodesReturnObj } from "@/tools/get-dict";

const removeKey = "remove";

export default {
  name: "preferential-allocation",
  setup() {
    const tableRef = ref();
    const { t } = useI18n();

    const router = useRouter();

    const toolbar = [
      {
        code: "preferential-allocation:add",
        label: t("preferentialAllocation.label.newPreferentialConfig"),
        type: "primary",
        event: (selectedRowKeys) => {
          handleAdd();
        },
      },
      // {
      //   code: "",
      //   label: t("button.delete"),
      //   type: "",
      //   event: (selectedRowKeys) => {
      //     handleExport();
      //   },
      // },
    ];

    const handleAdd = () =>
      router.push("/university/preferential-allocation/add");
    const handleExport = () => {};

    const columns = [
      {
        title: t("preferentialAllocation.label.preferentialName"),
        dataIndex: "preName",
        width: 160,
        key: "preName",
        ellipsis: true,
      },
      {
        title: t("preferentialAllocation.label.offerStartTime"),
        dataIndex: "preBtime",
        key: "preBtime",
        width: 160,
        ellipsis: true,
        cellRender: (record, data) => {
          return data ? moment(data).format("YYYY-MM-DD HH:mm:ss") : '';
        },
      },
      {
        title: t("preferentialAllocation.label.offerEndTime"),
        dataIndex: "preEtime",
        key: "preEtime",
        width: 160,
        ellipsis: true,
        cellRender: (record, data) => {
          return data ? moment(data).format("YYYY-MM-DD HH:mm:ss") : '';
        },
      },
      // {
      //   title: t("preferentialAllocation.label.typesOfPreferentialCourses"),
      //   dataIndex: "courseType",
      //   key: "courseType",
      //   width: 130,
      //   cellRender: (record, data) => {
      //     const item = dictLists.data[dictEnum.COURSE_TYPE]
      //       ? dictLists.data[dictEnum.COURSE_TYPE].find((v) => v.value == data)
      //       : {};
      //     return item ? item.label : "";
      //   },
      // },
      {
        title: t("preferentialAllocation.label.preferenceType"),
        dataIndex: "preType",
        key: "preType",
        width: 130,
        cellRender: (record, data) => {
          const item = dictLists.data[dictEnum.PRE_TYPE]
            ? dictLists.data[dictEnum.PRE_TYPE].find((v) => v.value == data)
            : {};
          return item ? item.label : "";
        },
      },
      // {
      //   title: t("preferentialAllocation.label.totalPriceCeilingAmount"),
      //   dataIndex: "maxAmt",
      //   key: "maxAmt",
      //   width: 120,
      // },
      {
        title: t("preferentialAllocation.label.preferentialAmount"),
        dataIndex: "preAmt",
        key: "preAmt",
        width: 120,
      },
      {
        title: t("preferentialAllocation.label.state"),
        dataIndex: "preStatus",
        key: "preStatus",
        width: 100,
        cellRender: (record, data) => {
          return data == 1 ? "启用" : "禁用";
        },
      },
      {
        title: t("preferentialAllocation.label.creator"),
        dataIndex: "createBy",
        key: "createBy",
        width: 130,
      },
      {
        title: t("preferentialAllocation.label.creationTime"),
        dataIndex: "createTime",
        key: "createTime",
        width: 160,
        cellRender: (record, data) => {
          return moment(data).format("YYYY-MM-DD HH:mm:ss");
        },
      },
    ];

    /// 数据来源 [模拟]
    const fetch = async (param) => {
      let response = await page(param);
      return {
        data: response.data.record,
      };
    };

    /// 删除配置
    const removeMethod = (record) => {
      modal.confirm({
        title: "您是否确定要删除此数据?",
        icon: createVNode(ExclamationCircleOutlined),
        okText: "确定",
        cancelText: "取消",
        onOk() {
          message.loading({ content: "提交中...", key: removeKey });
          remove({ id: record.id }).then((response) => {
            if (response.success) {
              message
                .success({ content: "删除成功", key: removeKey, duration: 1 })
                .then(() => {
                  tableRef.value.reload();
                });
            } else {
              message.error({
                content: "删除失败",
                key: removeKey,
                duration: 1,
              });
            }
          });
        },
      });
    };

    /// 行操作
    const operate = [
      {
        label: t("button.edit"),
        event: function ({ id }) {
          router.push({
            path: "/university/preferential-allocation/edit",
            query: { id: id },
          });
        },
      },
      {
        code: 'preferential-allocation:remove',
        label: t("button.delete"),
        event: function (record) {
          removeMethod(record);
        },
      },
    ];

    const pagination = {
      pageNum: 1,
      pageSize: 10,
    };

    const state = reactive({
      selectedRowKeys: [],
      param: {},
    });

    const searchParam = reactive({
      params: [],
    });

    const search = function (value) {
      state.param = {
        ...state.param,
        ...filterEmptyByObject(value),
        preBtime: value.createTime
          ? moment(value.createTime[0]).valueOf()
          : undefined,
        preEtime: value.createTime
          ? moment(value.createTime[1]).valueOf()
          : undefined,
      };
    };
    const onReset = function () {
      state.param = {};
    };

    const onSelectChange = (selectedRowKeys) => {
      state.selectedRowKeys = selectedRowKeys;
    };

    const dictLists = reactive({
      data: {}
    })
    onActivated(() => {
      tableRef.value.reload();
    })
    onMounted(async () => {
      dictLists.data = await getDictByCodesReturnObj([
        dictEnum.COURSE_TYPE, // 课程类型
        dictEnum.PRE_TYPE, // 优惠类型
        dictEnum.QUARTER, // 季度
        dictEnum.YEAR, // 年份
        dictEnum.SEMESTER_PERIOD, // 学期时段
        dictEnum.CREDITS, // 学分
      ]);

      searchParam.params = [
        {
          key: "preName",
          type: "input",
          label: t("preferentialAllocation.label.preferentialName"),
          placeholder: "请输入",
        },
        {
          key: "preType",
          type: "select",
          label: t("preferentialAllocation.label.preferenceType"),
          options: dictLists.data[dictEnum.PRE_TYPE],
          placeholder: "请选择",
        },
        {
          key: "courseType",
          type: "select",
          label: t("preferentialAllocation.label.typesOfPreferentialCourses"),
          options: dictLists.data[dictEnum.COURSE_TYPE],
          placeholder: "请选择",
        },
        {
          dataIndex: "createTime",
          key: "createTime",
          keys: ["preBtime", "preEtime"],
          type: "rangeTime",
          label: t("preferentialAllocation.label.preferentialTime"),
          showTime: { format: "HH:mm:ss" },
          format: "YYYY:MM:DD HH:mm:ss",
          valueFormat: "YYYY:MM:DD HH:mm:ss",
          hidden: true,
          placeholder: ["开始时间", "结束时间"],
        },
        {
          key: "state",
          type: "select",
          label: t("preferentialAllocation.label.enableStatus"),
          options: [
            { text: t("preferentialAllocation.label.enable"), value: 1 },
            { text: t("preferentialAllocation.label.disable"), value: 0 },
          ],
          placeholder: "请选择",
          hidden: true,
        },
      ];
    });
    return {
      t,
      state,
      fetch,
      search,
      onReset,
      columns,
      operate,
      pagination,
      searchParam,
      onSelectChange,
      toolbar,
      tableRef,
    };
  },
};
</script>
